﻿using System;
using System.Windows.Forms;
using Lidgren.Network;
using System.Collections.Generic;
using EclipseLib.Shared;
using System.Threading;
using Server.Management;

namespace Server
{
    public static class Network
    {
        // Data Members
        static ServerSocket socket;
        static ListBox logBox;
        static bool running;

        // Member Properties
        public static ServerSocket Socket
        {
            get { return socket; }
            private set { socket = value; }
        }
        public static ListBox LogBox
        {
            get { return logBox; }
            set { logBox = value; }
        }
        public static List<NetConnection> Clients
        {
            get { return Socket.Clients; }
        }
        public static bool Running
        {
            get { return running; }
            set { running = value; }
        }

        // Public Methods
        public static void InitServer(ListBox Log = null)
        {
            Socket = new ServerSocket();

            if (Log != null)
                LogBox = Log;

            AccountManager.Initialize();
            LogMessage("Initialized Accounts");

            running = true;
        }
        public static void Listen()
        {
            while (Running)
            {
                Socket.Listen();
                Thread.Sleep(1);
            }
        }
        public static void SendData(int Index, NetOutgoingMessage Packet)
        {
            Socket.SendData(Index, Packet);
        }
        public static void SendDataToAll(NetOutgoingMessage Packet)
        {
            Socket.SendDataToAll(Packet);
        }
        public static void SendDataToAllBut(int Index, NetOutgoingMessage Packet)
        {
            Socket.SendDataToAllBut(Index, Packet);
        }
        public static NetOutgoingMessage CreateMessage()
        {
            return Socket.CreateMessage();
        }
        public static NetOutgoingMessage CreateMessage(int Capacity)
        {
            return Socket.CreateMessage(Capacity);
        }
        public static NetOutgoingMessage CreateMessage(string Data)
        {
            return Socket.CreateMessage(Data);
        }
        public static void Close()
        {
            Socket.Close();
        }

        // Public Message Methods
        public static void LogMessage(string Message)
        {
            LogBox.BeginInvoke((MethodInvoker)(() =>
            {
                LogBox.Items.Add(DateTime.Now.ToShortTimeString() + ": " + Message);
            }));
        }
        public static void SendErrorMesage(int Index, string Message)
        {
            NetOutgoingMessage Packet = CreateMessage();
            Packet.Write((int)ServerPackets.SendErrorMessage);
            Packet.Write(Message);
            SendData(Index, Packet);
        }
    }
}
